#include <stdio.h>
//最小二乘值法
//编译：g++ -o run_polynomial_fitting polynomial_fitting.c

// 函数声明
void fitPolynomial(double points[3][2], double *coefficients);

int main() {
    // 三个点的坐标
    double points[3][2] = {
        {12895.000000, 3.778000}, // 点1
        {32614.000000, 9.361000}, // 点2
        {22871.000000, 6.402000}  // 点3
    };

    // 存储多项式系数的数组
    double coefficients[3];

    // 计算多项式系数
    fitPolynomial(points, coefficients);
    // 打印多项式表达式
    printf("1 Fitted polynomial: f(x) = %f x^2 + %f x + %f\n",
           coefficients[2], coefficients[1], coefficients[0]);

    return 0;
}

// 多项式三点拟合函数
void fitPolynomial(double points[3][2], double *coefficients) {
    // 使用三个点来设置线性方程组的系数
    double A[3][3] = {
        {points[0][0]*points[0][0], points[0][0], 1},
        {points[1][0]*points[1][0], points[1][0], 1},
        {points[2][0]*points[2][0], points[2][0], 1}
    };

    double B[3] = {points[0][1], points[1][1], points[2][1]};

    // 解线性方程组 A * coefficients = B
    // 由于我们只有三个方程和三个未知数，我们可以直接求解
    for (int i = 0; i < 3; i++) {
        coefficients[i] = (B[i] * A[(i+1)%3][1] * A[(i+2)%3][2] -
                           B[i] * A[(i+1)%3][2] * A[(i+2)%3][1] +
                           B[(i+1)%3] * A[i][1] * A[(i+2)%3][2] -
                           B[(i+1)%3] * A[i][2] * A[(i+2)%3][1] -
                           B[(i+2)%3] * A[i][1] * A[(i+1)%3][2] +
                           B[(i+2)%3] * A[i][2] * A[(i+1)%3][1]) /
                           (A[i][0] * A[(i+1)%3][1] * A[(i+2)%3][2] -
                            A[i][0] * A[(i+1)%3][2] * A[(i+2)%3][1] -
                            A[(i+1)%3][0] * A[i][1] * A[(i+2)%3][2] +
                            A[(i+1)%3][0] * A[i][2] * A[(i+2)%3][1] +
                            A[(i+2)%3][0] * A[i][1] * A[(i+1)%3][2] -
                            A[(i+2)%3][0] * A[i][2] * A[(i+1)%3][1]);
    }
}

